﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using TimerJobServerManager.Common;
using System;
using System.Windows.Input;

namespace TimerJobServerManager.ViewModel
{
    public class UpdateViewModel : ViewModelBase
    {
        //private UpdateManager updManager; //声明updateManager

        private string _MessageContent;

        /// <summary>
        /// 消息内容
        /// </summary>
        public string MessageContent
        {
            get { return _MessageContent; }
            set
            {
                Set("MessageContent", ref _MessageContent, value);
            }
        }

        public ICommand UpdateNowCommand { get; set; }
        public ICommand UpdateExitCommand { get; set; }


        public UpdateViewModel()
        {

            UpdateNowCommand = new RelayCommand(UpdateNow);
            UpdateExitCommand = new RelayCommand(UpdateExit);

            //AppContext.Context.AppSetting.IsPushVersionUpgrade;

            //获取文件更新的url地址
            var appUpgradeURL = ServerManagerConfig.Default.VersionUpdateURL;
            if (string.IsNullOrEmpty(appUpgradeURL))
            {
                this.MessageContent = "更新服务器URL配置为空，请检查修改更新配置。";
                return;
            }
            //updManager = UpdateManager.Instance;

            //// Only check for updates if we haven't done so already
            //if (updManager.State != UpdateManager.UpdateProcessState.NotChecked)
            //{
            //    updManager.CleanUp();
            //}

            //updManager.UpdateSource = PrepareUpdateSource(appUpgradeURL);
            //updManager.ReinstateIfRestarted();
            //try
            //{
            //    updManager.CheckForUpdates();
            //}
            //catch (Exception ex)
            //{
            //    //UpgradeEnabled = false;
            //    //LogManager.Write(ex);
            //    this.MessageContent =
            //       string.Format("版本更新服务器{0}连接失败！n请检查修改更新配置信息。", appUpgradeURL);
            //    return;
            //}

            if (true)//updManager.UpdatesAvailable == 0)
            {
                var currentVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
                this.MessageContent = string.Format("已经是最新的版本{0} 没有可用的更新。", currentVersion);
            }
            else
            {
                //this.UpgradeEnabled = true;

                //var updateTaskHelper = new UpdateTaskHelper();//自定义一个TaskHelper类负责合并处理版本描述信息。
                //var desc = updateTaskHelper.UpdateDescription;
                //var currentVersion = updateTaskHelper.CurrentVersion;

                //this.MessageContent = string.Format("有可更新的版本，更新文件数量： ({0}) 版本描述：n{1} 。",
                //     updManager.UpdatesAvailable, desc);
                //var taskInfo = updateTaskHelper.TaskListInfo;
            }
        }

        /// <summary>
        /// 立即更新
        /// </summary>
        private void UpdateNow()
        {
            //ShowThrobber();
            // dummy time delay for demonstration purposes
            //var t = new System.Timers.Timer(2000) { AutoReset = false };
            //t.Start();
            //while (t.Enabled) { DoEvents(); }

            //updManager.BeginPrepareUpdates(asyncResult =>
            //{
            //    ((UpdateProcessAsyncResult)asyncResult).EndInvoke();

            //    // ApplyUpdates is a synchronous method by design. Make sure to save all user work before calling
            //    // it as it might restart your application
            //    // get out of the way so the console window isn't obstructed
            //    try
            //    {
            //        updManager.ApplyUpdates(true);

            //        //if (Dispatcher.CheckAccess())
            //        //{
            //        //    Close();
            //        //}
            //        //else
            //        //{
            //        //    //Dispatcher.Invoke(new Action(Close));
            //        //}
            //    }
            //    catch
            //    {
            //        MessageBox.Show("An error occurred while trying to install software updates");
            //    }
            //    finally
            //    {
            //        updManager.CleanUp();
            //    }
            //}, null);
        }

        

        /// <summary>
        /// 退出后更新
        /// </summary>
        private void UpdateExit()
        {
            throw new NotImplementedException();
        }

        //private IUpdateSource PrepareUpdateSource(string appUpgradeURL)
        //{
        //    // Normally this would be a web based source.
        //    // But for the demo app, we prepare an in-memory source.
        //    var source = new NAppUpdate.Framework.Sources.SimpleWebSource(appUpgradeURL);
        //    //var source = new VersionUpdateSource(url);
        //    return source;

        //}
    }
}
